package com.hdjk.view.activity.personalcenter;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.hdjk.view.R;
import com.hdjk.view.adapter.RedeemConfigAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.dialog.EditTextPwdDialog;
import com.hdjk.view.entity.BankEntity;
import com.hdjk.view.entity.HoldingFundEntity;
import com.hdjk.view.entity.PayMethodEntity;
import com.hdjk.view.entity.RedeemFee;
import com.hdjk.view.entity.SellResult;
import com.hdjk.view.network.FundNetWork;
import com.hdjk.view.network.Network;
import com.hdjk.view.network.RedeemNetwork;
import com.hdjk.view.network.TransactionNetWork;
import com.hdjk.view.util.SharedPreferencesUtil;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.component.ListView.ListViewForScrollView;
import com.lst.projectlib.entity.Msg;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

/**
 * Created by Administrator on 2017/11/21.
 */

public class RedeemConfirmActivity extends BaseActivity implements View.OnClickListener {

    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private TextView tv_bank_info, tv_money, tv_rate, tv_cost, tv_redeem;
    private TextView tv_yifeng;
    private ListViewForScrollView lv_data_list;
    private RedeemConfigAdapter mAdapter;

    private List<BankEntity> mList;
    private List<BankEntity> mBankList;
    private String title, portfolioId, fundCode, type, money;
    private List<HoldingFundEntity> funds;
    private PayMethodEntity payMethod;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_redeem_confirm);
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        tv_bank_info = (TextView) findViewById(R.id.tv_bank_info);
        tv_money = (TextView) findViewById(R.id.tv_money);
        tv_rate = (TextView) findViewById(R.id.tv_rate);
        tv_cost = (TextView) findViewById(R.id.tv_cost);
        tv_redeem = (TextView) findViewById(R.id.tv_redeem);
        tv_yifeng = (TextView) findViewById(R.id.tv_yifeng);
        tv_redeem.setOnClickListener(this);
        tv_yifeng.setOnClickListener(this);
        lv_data_list = (ListViewForScrollView) findViewById(R.id.lv_data_list);
    }

    @Override
    protected void initData() {
        mDialog.show();
        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        ((TextView) ttb_title_bar.findViewById(R.id.tvNavTitle)).setText(title);
        portfolioId = intent.getStringExtra("portfolioId");
        fundCode = intent.getStringExtra("fundCode");
        type = intent.getStringExtra("type");
        money = intent.getStringExtra("money");
        funds = (List<HoldingFundEntity>) getIntent().getSerializableExtra("funds");
        mAdapter = new RedeemConfigAdapter(RedeemConfirmActivity.this, money);
        mAdapter.setDataList(funds);
        lv_data_list.setAdapter(mAdapter);

        getBankList();

        if (type.equals("0") || type.equals("1")) {
            getRedeemSellFee();
            tv_rate.setVisibility(View.VISIBLE);
        } else {
            tv_rate.setVisibility(View.GONE);
            getRedeemTransactionFee();
        }
    }

    private void getRedeemTransactionFee() {
        JSONObject object = new JSONObject();
        try {
            object.put("accountNumber", UserTokenUtil.getUserName(RedeemConfirmActivity.this));
            object.put("portfolioId", portfolioId);
            FundNetWork.getRedeemTransactionFee(UserTokenUtil.getToken(RedeemConfirmActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.dismiss();

                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof RedeemFee) {
                        RedeemFee redeemFee = (RedeemFee) msg.getData();
                        tv_cost.setText("预计费用：" + redeemFee.getRedemptionCharge() + "元");
                    } else if (msg != null && msg.getMsg() != null && !msg.getMsg().equals("")) {
                        Toast.makeText(RedeemConfirmActivity.this, msg.getMsg(), Toast.LENGTH_SHORT).show();
                        tv_redeem.setVisibility(View.GONE);
                    } else {
                        tv_redeem.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getRedeemSellFee() {
        JSONObject object = new JSONObject();
        try {
            object.put("accountNumber", UserTokenUtil.getUserName(RedeemConfirmActivity.this));
            object.put("fundCode", fundCode);
            object.put("redemptionUnit", funds.get(0).getAvailableUnit());
            FundNetWork.getRedeemSellFee(UserTokenUtil.getToken(RedeemConfirmActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.dismiss();

                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof RedeemFee) {
                        RedeemFee redeemFee = (RedeemFee) msg.getData();

                        if (funds.get(0).getChargeMode().equals("0")) {
                            tv_rate.setText("参考费率：" + redeemFee.getAvgRedemptionChargeRate() + "%");
                            tv_cost.setText("预计费用：" + redeemFee.getRedemptionCharge() + "元");
                        } else {
                            tv_rate.setText("参考费率：" + redeemFee.getBackendRate() + "%");
                            tv_cost.setText("预计费用：" + redeemFee.getBackendCharges() + "元");
                        }
                    } else if (msg != null && msg.getMsg() != null && !msg.getMsg().equals("")) {
                        Toast.makeText(RedeemConfirmActivity.this, msg.getMsg(), Toast.LENGTH_SHORT).show();
                        tv_redeem.setVisibility(View.GONE);
                    } else {
                        tv_redeem.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getBankList() {
        mBankList = SharedPreferencesUtil.getBankList(this);
        if (mBankList == null || mBankList.size() == 0) {
            Network.getBankList(UserTokenUtil.getToken(RedeemConfirmActivity.this), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    if (msg != null) {
                        if (msg.getSuccess()) {
                            if (!TextUtils.isEmpty(msg.getResult()))
                                SharedPreferencesUtil.saveBankList(RedeemConfirmActivity.this, msg.getResult());
                            mBankList = (List<BankEntity>) msg.getData();
                            getPayMethod();
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } else {
            getPayMethod();
        }
    }

    private void getPayMethod() {
        JSONObject object = new JSONObject();
        try {
            object.put("accountNumber", UserTokenUtil.getUserName(RedeemConfirmActivity.this));
            TransactionNetWork.getPayMethod(UserTokenUtil.getToken(RedeemConfirmActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof PayMethodEntity) {
                        payMethod = (PayMethodEntity) msg.getData();
                        if (payMethod.getInvestorBankDetails() != null && payMethod.getInvestorBankDetails().getData() != null) {
                            mList = payMethod.getInvestorBankDetails().getData();
                            for (int i = 0; i < mList.size(); i++) {
                                BankEntity bankCard = mList.get(i);
                                for (int j = 0; j < mBankList.size(); j++) {
                                    BankEntity bank = mBankList.get(j);
                                    if (bankCard.getBankCode().equals(bank.getBankCode())) {
                                        tv_bank_info.setText("尾号 " + bankCard.getBankNumber().substring(bankCard.getBankNumber().length() - 4) + " " + bank.getName() + "卡");
                                        tv_money.setText(money + "元");
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.tv_yifeng:
                showPopupWindow(tv_yifeng);
                break;
            case R.id.tv_redeem:
                if (type.equals("0")) {
                    showFundPwdDialog();
                } else if (type.equals("1")) {
                    showCollectivePwdDialog();
                } else if (type.equals("2")) {
                    showPortfolioPwdDialog();
                }

                break;
        }
    }

    private void showFundPwdDialog() {
        EditTextPwdDialog dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
            @Override
            public void onSureClick(String txt) {
                mDialog.show();
                JSONObject object = new JSONObject();
                try {
                    object.put("accountNumber", UserTokenUtil.getUserName(RedeemConfirmActivity.this));
                    object.put("investorPayId", payMethod.getInvestorBankDetails().getData().get(0).getInvestorPayId());
                    object.put("password", txt);
                    object.put("payMethod", "0");

                    JSONArray array = new JSONArray();
                    JSONObject sellFund = new JSONObject();
                    sellFund.put("fundCode", funds.get(0).getFundCode());
                    sellFund.put("redemptionUnit", funds.get(0).getAvailableUnit());
                    array.put(sellFund);

                    object.put("sellFunds", array);
                    RedeemNetwork.redeemFund(UserTokenUtil.getToken(RedeemConfirmActivity.this), object.toString(), new CallBackListener() {
                        @Override
                        public void onCallBackCompleted(Msg msg) {
                            mDialog.cancel();
                            if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof List) {
                                List<SellResult> sellResults = (List<SellResult>) msg.getData();
                                Intent intent = new Intent(RedeemConfirmActivity.this, RedeemSuccessActivity.class);
                                intent.putExtra("sellResults", (Serializable) sellResults);
                                startActivityForResult(intent, 1001);
                            } else if (msg != null && msg.getMsg() != null && !msg.getMsg().equals("")) {
                                Toast.makeText(RedeemConfirmActivity.this, msg.getMsg(), Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(RedeemConfirmActivity.this, "赎回失败！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onCallBackError(Msg msg) {
                            mDialog.cancel();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.show();
    }

    private void showCollectivePwdDialog() {
        EditTextPwdDialog dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
            @Override
            public void onSureClick(String txt) {
                mDialog.show();
                JSONObject object = new JSONObject();
                try {
                    object.put("accountNumber", UserTokenUtil.getUserName(RedeemConfirmActivity.this));
                    object.put("fundCode", funds.get(0).getFundCode());
                    object.put("investorPayId", payMethod.getInvestorBankDetails().getData().get(0).getInvestorPayId());
                    object.put("password", txt);
                    object.put("redemptionUnit", funds.get(0).getAvailableUnit());
                    object.put("sellMode", "0");

                    RedeemNetwork.redeemCollective(UserTokenUtil.getToken(RedeemConfirmActivity.this), object.toString(), new CallBackListener() {
                        @Override
                        public void onCallBackCompleted(Msg msg) {
                            mDialog.cancel();
                            if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof List) {
                                List<SellResult> sellResults = (List<SellResult>) msg.getData();
                                Intent intent = new Intent(RedeemConfirmActivity.this, RedeemSuccessActivity.class);
                                intent.putExtra("sellResults", (Serializable) sellResults);
                                startActivityForResult(intent, 1001);
                            } else if (msg != null && msg.getMsg() != null && !msg.getMsg().equals("")) {
                                Toast.makeText(RedeemConfirmActivity.this, msg.getMsg(), Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(RedeemConfirmActivity.this, "赎回失败！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onCallBackError(Msg msg) {
                            mDialog.cancel();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.show();
    }

    private void showPortfolioPwdDialog() {
        EditTextPwdDialog dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
            @Override
            public void onSureClick(String txt) {
                mDialog.show();
                JSONObject object = new JSONObject();
                try {
                    object.put("accountNumber", UserTokenUtil.getUserName(RedeemConfirmActivity.this));
                    object.put("investorPayId", payMethod.getInvestorBankDetails().getData().get(0).getInvestorPayId());
                    object.put("password", txt);
                    object.put("paymentMethod", "0");
                    object.put("portfolioId", portfolioId);

                    RedeemNetwork.redeemPortfolio(UserTokenUtil.getToken(RedeemConfirmActivity.this), object.toString(), new CallBackListener() {
                        @Override
                        public void onCallBackCompleted(Msg msg) {
                            mDialog.cancel();
                            if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof List) {
                                List<SellResult> sellResults = (List<SellResult>) msg.getData();
                                Intent intent = new Intent(RedeemConfirmActivity.this, RedeemSuccessActivity.class);
                                intent.putExtra("sellResults", (Serializable) sellResults);
                                startActivityForResult(intent, 1001);
                            } else if (msg != null && msg.getMsg() != null && !msg.getMsg().equals("")) {
                                Toast.makeText(RedeemConfirmActivity.this, msg.getMsg(), Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(RedeemConfirmActivity.this, "赎回失败！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onCallBackError(Msg msg) {
                            mDialog.cancel();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1002) {
            setResult(1002);
            back();
        }
    }
}
